﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Core.Service;
using Microsoft.AspNetCore.Http;
namespace Admin.NET.Application;

/// <summary>
/// 项目服务
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class ProjectService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<Project> _projectRep;
    private readonly SqlSugarRepository<Device> _deviceRep;
    private readonly IClientWebSocketManager _clientWebSocketManager;
    public ProjectService(SqlSugarRepository<Project> projectRep, IClientWebSocketManager clientWebSocketManager, SqlSugarRepository<Device> deviceRep)
    {
        _projectRep = projectRep;
        _clientWebSocketManager = clientWebSocketManager;
        _deviceRep = deviceRep;
    }

    /// <summary>
    /// 分页查询项目
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Page")]
    [DisplayName("分页查询项目")]
    public async Task<SqlSugarPagedList<ProjectOutput>> Page(PageProjectInput input)
    {
		input.SearchKey = input.SearchKey?.Trim();
        var query = _projectRep.AsQueryable()
            .WhereIF(!string.IsNullOrEmpty(input.SearchKey), u =>
                u.Name.Contains(input.SearchKey)
                || u.ServerIP.Contains(input.SearchKey)
                || u.ServerPort.Contains(input.SearchKey)
                || u.ManufacturerId.Contains(input.SearchKey)
            )
            .WhereIF(!string.IsNullOrWhiteSpace(input.Name), u => u.Name.Contains(input.Name.Trim()))
            .WhereIF(input.Status.HasValue, u => u.Status == input.Status)
            .WhereIF(!string.IsNullOrWhiteSpace(input.ServerIP), u => u.ServerIP.Contains(input.ServerIP.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.ServerPort), u => u.ServerPort.Contains(input.ServerPort.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.ManufacturerId), u => u.ManufacturerId.Contains(input.ManufacturerId.Trim()))
            //.Select<ProjectOutput>();
            .Select(it => new ProjectOutput()
            {
                EmpCount = SqlFunc.Subqueryable<Employee>().Where(u=>u.ProjectId == it.Id).Count(),
                MobileEmpCount = SqlFunc.Subqueryable<Employee>().Where(u => u.ProjectId == it.Id && u.IsMobile == true).Count(),
                TodayUploadCount = SqlFunc.Subqueryable<UploadLog>().Where(u=>u.CreateTime.Date==DateTime.Now.Date && u.ProjectId == it.Id ).Count(),
                NotUploadCount = SqlFunc.Subqueryable<UploadLog>().Where(u => u.ProjectId == it.Id && u.IsUpload == false).Count(),
                UploadErrCount = SqlFunc.Subqueryable<UploadLog>().Where(u => u.ProjectId == it.Id && u.IsUploadErr == true).Count(),
                DeviceCount = 0,
                OnlineDeviceCount = 0
            }, true);
        var queryResult = await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);

        foreach (var project in queryResult.Items)
        {
            List<string> deviceSnList = _deviceRep.AsQueryable()
                .Where(u => u.ProjectId == project.Id)
                .Select(it => it.ClientSn).ToList();

            // 获取在线设备的 ClientSn 列表  
            var onlineDeviceSnList = _clientWebSocketManager.SelectAllConnections().Keys.ToList();
            // 计算 deviceSnList 中存在于 onlineDeviceSnList 的数量  
            int onlineCount = deviceSnList.Count(sn => onlineDeviceSnList.Contains(sn));
            project.OnlineDeviceCount = onlineCount;
            project.DeviceCount = deviceSnList.Count();
        }

        return queryResult;
    }

    /// <summary>
    /// 增加项目
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Add")]
    [DisplayName("增加项目")]
    public async Task<long> Add(AddProjectInput input)
    {
        var entity = input.Adapt<Project>();
        await _projectRep.InsertAsync(entity);
        return entity.Id;
    }

    /// <summary>
    /// 删除项目
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Delete")]
    [DisplayName("删除项目")]
    public async Task Delete(DeleteProjectInput input)
    {
        var entity = await _projectRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _projectRep.FakeDeleteAsync(entity);   //假删除
        //await _projectRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 更新项目
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Update")]
    [DisplayName("更新项目")]
    public async Task Update(UpdateProjectInput input)
    {
        var entity = input.Adapt<Project>();
        await _projectRep.AsUpdateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
    }

    /// <summary>
    /// 获取项目
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "Detail")]
    [DisplayName("获取项目")]
    public async Task<Project> Detail([FromQuery] QueryByIdProjectInput input)
    {
        return await _projectRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 获取项目列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "List")]
    [DisplayName("获取项目列表")]
    public async Task<List<ProjectOutput>> List([FromQuery] PageProjectInput input)
    {
        return await _projectRep.AsQueryable().Select<ProjectOutput>().ToListAsync();
    }





}
